package com.dai.rpc.proxy;

import com.dai.rpc.annotation.MyMapping;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyHttpClientProxy implements InvocationHandler {


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("执行了代理逻辑。。。");
        // 判断方法上的注解是否是@MyMapping
        MyMapping annotation = method.getAnnotation(MyMapping.class);
        if(annotation != null){
            String api = annotation.api();
            String url = annotation.url();
            // 使用正则表达式匹配url，替换参数
            Pattern compile = Pattern.compile("(\\{\\w+})");
            Matcher matcher = compile.matcher(api);
            if (matcher.find()){
                //简单判断一下 代表有路径参数需要替换
                int x = matcher.groupCount();
                for (int i = 0; i< x; i++){
                    String group = matcher.group(i);
                    // 方法上的参数
                    api = api.replace(group, args[i].toString());
                }
            }
            RestTemplate restTemplate = new RestTemplate();
            return restTemplate.getForObject(url + api,method.getReturnType());
        }
        return null;
    }

    public <T> T getProxy(Class<T> interfaceClass) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[]{interfaceClass}, this);
    }
}
